package com.hzh.page.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzh.page.common.enums.RightEnum;
import com.hzh.page.common.exception.ResponseEnum;
import com.hzh.page.common.utils.MD5;
import com.hzh.page.common.utils.R;
import com.hzh.page.common.valid.AddValidGroup;
import com.hzh.page.common.valid.UpdateValidGroup;
import com.hzh.page.pojo.AuthenticationUser;
import com.hzh.page.pojo.AuthenticationUserRoleEntity;
import com.hzh.page.service.AuthenticationMenuService;
import com.hzh.page.service.AuthenticationUserRoleService;
import com.hzh.page.service.AuthenticationUserService;
import com.hzh.page.vo.AuthenticationUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 接口
 *
 * @author chenzw
 * @date 2022-11-03
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping(value = "/page/admin/user")
public class AuthenticationUserController {

    @Autowired
    private AuthenticationUserService userService;

    @Autowired
    private AuthenticationUserRoleService userRoleService;

    @Autowired
    private AuthenticationMenuService menuService;

    @ApiOperation("添加用户")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/add")
    public R addUser(@Validated({AddValidGroup.class}) @RequestBody AuthenticationUserVO userVO, HttpServletRequest request) {

        boolean hashAuthority = menuService.hashAuthority(request, RightEnum.USER_MANAGE_ADD.getRoute_key());
        if (!hashAuthority) {
            return R.error(ResponseEnum.NO_RIGHT.getMessage());
        } else {
            AuthenticationUser hasUser = userService.getOne(new QueryWrapper<AuthenticationUser>().eq("user_name", userVO.getUserName()));
            if (hasUser != null) {
                return R.error(ResponseEnum.LOGIN_USER_EXIST.getMessage());
            } else {
                AuthenticationUser user = new AuthenticationUser();
                BeanUtils.copyProperties(userVO, user);
                user.setPassWord(MD5.encrypt(userVO.getPassWord()));
                userService.save(user);

                AuthenticationUserRoleEntity userRoleEntity = new AuthenticationUserRoleEntity();
                userRoleEntity.setRoleId(userVO.getRoleId());
                userRoleEntity.setUserId(user.getId());
                userRoleService.save(userRoleEntity);
            }
            return R.ok("添加成功");
        }

    }

    @ApiOperation("修改用户")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/update")
    public R updateUser(@Validated({UpdateValidGroup.class}) @RequestBody AuthenticationUserVO userVO, HttpServletRequest request) {
        boolean hashAuthority = menuService.hashAuthority(request, RightEnum.USER_MANAGE_UPDATE.getRoute_key());
        if (!hashAuthority) {
            return R.error(ResponseEnum.NO_RIGHT.getMessage());
        }
        userService.updateUser(userVO);
        return R.ok("修改成功");
    }

    @ApiOperation("修改用户状态")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestParam Integer userId, @RequestParam Boolean roleState, HttpServletRequest request) {
        boolean hashAuthority = menuService.hashAuthority(request, RightEnum.USER_MANAGE_UPDATE.getRoute_key());
        if (!hashAuthority) {
            return R.error(ResponseEnum.NO_RIGHT.getMessage());
        }
        userService.updateStatus(userId, roleState);
        return R.ok("修改成功");
    }

    @ApiOperation("删除用户")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/delete/{userId}")
    public R deleteUser(@PathVariable("userId") Integer userId, HttpServletRequest request) {
        boolean hashAuthority = menuService.hashAuthority(request, RightEnum.USER_MANAGE_DELETE.getRoute_key());
        if (!hashAuthority) {
            return R.error(ResponseEnum.NO_RIGHT.getMessage());
        }
        userService.deleteUser(userId);
        return R.ok("删除成功");
    }

    @ApiOperation("获取用户信息")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/userInfo/{id}")
    public R userInfo(@PathVariable("id") Integer id) {
        AuthenticationUserVO userVO = userService.getUserInfoById(id);
        if (userVO != null) {
            return R.ok().put("userVO", userVO);
        } else {
            return R.error(ResponseEnum.LOGIN_MOBILE_ERROR.getMessage());
        }
    }

    @ApiOperation("获取用户信息列表")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/userList/{page}/{limit}")
    public R userList(@ApiParam(value = "当前页码", required = true)
                      @PathVariable Long page,
                      @ApiParam(value = "每页记录数", required = true)
                      @PathVariable Long limit,
                      HttpServletRequest request) {

        Page<AuthenticationUser> pageParam = new Page<>(page, limit);
        IPage<AuthenticationUserVO> pageModel = userService.listPage(pageParam,request);
        return R.ok().put("userList", pageModel);
    }

}
